﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XmppConsoleTest
{
    class LightAndCarTest3
    {
        static void Main()
        {
            var light = new Light();
            var car1 = new Car();
            car1.Name = "轿车1";
            var car2 = new Car();
            car2.Name = "公交车1";
            List<Car> cars  = new List<Car>() { car1,car2};
            light.ColorChanged += sender =>
            {
                if (light.Color == "red")
                {
                    foreach (Car c in cars)
                    {
                        c.Stop();
                    }
                }
                if (light.Color == "green")
                {
                    foreach (Car c in cars)
                    {
                        c.Go();
                    }
                }

            };

            while (true)
            {
                light.ChangeColor();
                Thread.Sleep(5000);
            }
        }
    }

    class Car
    {
        public string Name { get; set; }

        public string State { get; set; }


        public void Stop()
        {
            this.State = "stop";
            this.ShowState();
        }

        public void Go()
        {
            this.State = "go";
            this.ShowState();
        }

        void ShowState()
        {
            Console.WriteLine($"{Name}当前状态{State}");
        }
    }

    delegate void LightChangeColor(Light light);

    class Light
    {
        public event LightChangeColor ColorChanged;
        public string Color { get; set; }

        public void ChangeColor()
        {
            if (Color == "red")
            {
                Color = "green";
            }
            else
            {
                Color = "red";
            }
            Console.WriteLine("当前交通灯的颜色:" + Color);
            if (ColorChanged != null)
            {
                this.ColorChanged(this);
            }
        }
    }
}

